﻿using Architecture.Common;
using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.User;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.User
{
    public class UserLoginHandler : IRequestHandler<UserLoginCommand, ApiResult<UserLoginDto>>
    {
        private readonly IBaseRepository<UsersModel> _userRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        private readonly IBaseRepository<RoleModel> _RoleRepository;
        private readonly IMapper _mapper;
        private readonly JwtTools _jwtTools;
        private readonly IConfiguration _configuration;
        public UserLoginHandler(IBaseRepository<UsersModel> userRepository, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<RoleModel> roleRepository, IMapper mapper, JwtTools jwtTools, IConfiguration configuration)
        {
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _RoleRepository = roleRepository;
            _mapper = mapper;
            _jwtTools = jwtTools;
            _configuration = configuration;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<UserLoginDto>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserLoginDto>result =new ApiResult<UserLoginDto>();

            var user = _userRepository.GetAll().Where(p=>p.UserName==request.UserName).FirstOrDefault();
            if(user == null)
            {
                result.Code=StatusEnum.Error;
                result.Message = "用户名不存在";
                return Task.FromResult(result);
            }
            if(user.UserPwd!=request.UserPwd)
            {
                result.Code = StatusEnum.Error;
                result.Message = "用户密码错误";
                return Task.FromResult(result);
            }
            var model =_mapper.Map<UserLoginDto>(user);
            model.UserId = user.Id;
            model.RoleId=_userRoleRepository.GetAll().Where(p=>p.UserId==user.Id).Select(p=>p.RoleId).ToList();
            model.RoleName = string.Join(',', _RoleRepository.GetAll().Where(p => model.RoleId.Contains(p.Id)).Select(p => p.RoleName));
            model.Token = _jwtTools.JwtNewString(_configuration, user.Id.ToString());


            result.Code=StatusEnum.OK;
            result.Data = model;
            result.Message = "登录成功";
            return Task.FromResult(result);
        }
    }
}
